package com.toKnow.service.impl;

import com.toKnow.mapper.ArticleMapper;
import com.toKnow.mapper.ColumnMapper;
import com.toKnow.mapper.SearchHistoryMapper;
import com.toKnow.model.dto.SearchDto;
import com.toKnow.model.entity.Column;
import com.toKnow.model.vo.RestrictionVo;
import com.toKnow.service.ColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ColumnServiceImpl implements ColumnService {
    @Autowired
    ColumnMapper columnMapper;
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    SearchHistoryMapper historyMapper;

    @Override
    public Column getColumn(Integer id) {
        if (id==null) return null;
        Column column = columnMapper.selectById(id);
        if (column==null) return null;
        column.setTagList(columnMapper.selectTagById(id));
        column.setTypeList(columnMapper.selectTypeById(id));
        column.setArticleIdList(articleMapper.selectArticleByColumnId(id,null));
        return column;
    }

    @Override
    public Boolean changeCollectColumn(Integer userId, Integer columnId) {
        if (userId==null||columnId==null) return false;
        if (isCollectColumn(userId, columnId)){
            columnMapper.updateCollectNumber(columnId,-1);
            return columnMapper.deleteUserCollect(userId, columnId);
        }else{
            columnMapper.updateCollectNumber(columnId,1);
            return columnMapper.insertUserCollect(userId, columnId);
        }
    }

    @Override
    public Boolean isCollectColumn(Integer userId, Integer columnId) {
        if (userId==null||columnId==null) return false;
        return columnMapper.checkUserCollect(userId, columnId);
    }

    @Transactional(readOnly = false)
    @Override
    public List<Column> searchColumn(Integer uid,RestrictionVo restrictionVo) {
        String content=restrictionVo.getKeyword();
        if (content!=null&&uid!=null) historyMapper.insertSearchHistory(uid,content);
        return columnMapper.selectColumnBySearch(new SearchDto(restrictionVo,"column"));
    }
}
